package serviceImpl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import mapper.InformMapper;
import mapper.GroupMapper;
import mapper.TaskMapper;
import mapper.UserMapper;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import controller.Vo.GroupUserVo;
import controller.Vo.TaskUsersVo;
import controller.Vo.UserInfromVo;
import controller.Vo.UserTaskVo;
import service.NoteService;
import service.ServiceException;
import entity.Group;
import entity.Inform;
import entity.Task;
import entity.User;
import entity.UserTask;

@Service
public class NoteServiceImpl implements NoteService{
	private static final Logger logger = Logger.getLogger(NoteServiceImpl.class);
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private GroupMapper groupMapper;
	@Autowired
	private InformMapper informMapper;
	@Autowired
	private TaskMapper taskMapper;
	@Value("${group.uploadFilePath}")
	private String rootDir;
	
	@Override
	public User selectUserByUserName(String username,String password){
		try{
			User user = userMapper.selectUserByUserName(username);
			if(user == null){
				return null;
			}
			if(password != null){
				if(password.equals(user.getPassword())){
					return user;
				}
			}
			return null;
		}catch(Exception e){
			throw new ServiceException("查询用户失败",e);
		}
	}
	
	@Override
	@Transactional
	public Group addGroup(String groupName, int[] userIds, int createUserId) {
		try{
			if(StringUtils.isNotBlank(groupName)){
				Group group = groupMapper.selectGroupByNameUserId(groupName,createUserId);
				if(group != null){
					throw new ServiceException("该分组名已经存在");
				}
				File groupRootDir = new File(rootDir);
				File groupDir = new File(groupRootDir,groupName.trim());
				if(!groupDir.isDirectory()){
					groupDir.mkdirs();
				}
				
				Group newGroup = new Group();
				newGroup.setName(groupName);
				newGroup.setCreateUserId(createUserId);
				newGroup.setCreateTime(new Date());
				groupMapper.addGroup(newGroup);
				
				group = groupMapper.selectGroupByNameUserId(groupName,createUserId);
				groupMapper.addUserGroup(group.getId(),createUserId);
				if(userIds != null){
					for(int userId : userIds){
						groupMapper.addUserGroup(group.getId(),userId);
					}
				}
				return group;
			}else{
				return null;
			}
		}catch(Exception e){
			throw new ServiceException("添加组群失败,可能原因是组名重复",e);
		}
	}

	@Override
	public List<User> selectCurrentGroupMembers(Integer groupId) {
		try{
			if(groupId != null){
				List<User> users = new ArrayList<User>();
				List<Integer> userIds = groupMapper.selectUserIdsByGroupId(groupId);
				for(int userId : userIds){
					User user = userMapper.selectUserByUserId(userId);
					users.add(user);
				}
				return users;
			}
			return null;
		}catch(Exception e){
			throw new ServiceException("查询组内成员失败",e);
		}
	}

	@Override
	@Transactional
	public void updateGroupMembers(Integer groupId, int[] userIds) {
		try{
			if(groupId != null){
				List<Integer> groupUserIds = groupMapper.selectUserIdsByGroupId(groupId);
				for(int groupUserId : groupUserIds){
					groupMapper.deleteGroupUser(groupId, groupUserId);
				}
				
				if(userIds != null){
					for(int userId : userIds){
						groupMapper.addUserGroup(groupId,userId);
					}
				}else{
					throw new ServiceException("需添加的用户id不能为空");
				}
				
			}else{
				throw new ServiceException("需更新的组id不能为空");
			}
		}catch(Exception e){
			throw new ServiceException("更新组成员失败", e);
		}
	}
	
	@Override
	public List<GroupUserVo> showJoinGroups(User user) {
		try {
			List<GroupUserVo> groupUsers = new ArrayList<GroupUserVo>();
			if(user != null){
				List<Integer> groupIds = groupMapper.selectGroupIdsByUser(user);
				for(int groupId : groupIds){
					Group group = groupMapper.selectGroupByGroupId(groupId);
					User createUser = userMapper.selectUserByUserId(group.getCreateUserId());
					GroupUserVo groupUser = new GroupUserVo();
					
					groupUser.setGroup(group);
					groupUser.setUser(createUser);
					groupUsers.add(groupUser);
				}
			}
			return 	groupUsers;
		} catch (Exception ex){
			throw new ServiceException("查询失败",ex);
		}
	}
	
	/**
	 * 事务管理
	 */
	
	@Override
	public List<GroupUserVo> showAllContacts() {
		List<GroupUserVo> groupUsers = new ArrayList<GroupUserVo>();
		List<Group> groups = groupMapper.selectAllGroups();
		for(Group group : groups){
			List<User> users = selectCurrentGroupMembers(group.getId());
			if(users != null && users.size()>0){
				GroupUserVo groupUser = new GroupUserVo();
				groupUser.setGroup(group);
				groupUser.setUsers(users);
				groupUsers.add(groupUser);
			}
		}
		GroupUserVo noGroupUsers = selectNoGroupUsers();
		if(noGroupUsers != null){
			groupUsers.add(noGroupUsers);
		}
		return groupUsers;
	}
	
	/*
	 * 查询没有在分组里面的成员
	 */
	private GroupUserVo selectNoGroupUsers(){
		List<User> noGroupsUsers = new ArrayList<User>();
		List<Integer> userIds = groupMapper.selectAllGroupUserIds();
		List<User> users = userMapper.selectAllUsers();
		for(User user : users){
			if(!userIds.contains(user.getId())){
				User currentUser = userMapper.selectUserByUserId(user.getId());
				noGroupsUsers.add(currentUser);
			}
		}
		if(noGroupsUsers.size() > 0){
			Group group = new Group();
			group.setName("未有分组的用户");
			GroupUserVo groupUser = new GroupUserVo();
			groupUser.setGroup(group);
			groupUser.setUsers(noGroupsUsers);
			return groupUser;
		}
		return null;
	}
	
	@Override
	public List<User> getChooseUsers(int[] ids) {
		Set<Integer> userIds = removeRepeatIds(ids);
		List<User> users = new ArrayList<User>();
		for(int userId : userIds){
			User user = userMapper.selectUserByUserId(userId);
			users.add(user);
		}
		
		return users;
	}
	
	private Set<Integer> removeRepeatIds(int[] ids){
		Set<Integer> result = new HashSet<Integer>();
		for(int id : ids){
			result.add(id);
		}
		return result;
	}


//	@Override
//	public List<GroupNoteVo> nofinishedNotes(User user) {
//		try {
//			List<GroupNoteVo> groupNotes = new ArrayList<>();
//			List<Integer> groupIds = groupMapper.selectAllGroupsByUserId(user.getId());
//			if(groupIds != null && groupIds.size() > 0){
//				for(int groupId : groupIds){
//					Group group= groupMapper.selectGroupByGroupId(groupId);
//					List<Integer> noteIds = noteMapper.selectNoteIdByGroupId(group.getId());
//					
//					if(noteIds != null && noteIds.size() > 0){
//						List<UserNote> userNotes = new ArrayList<>();
//						for (int noteId : noteIds) {
//							Note note = noteMapper.selectNoteById(noteId);
//							User noteUser = userMapper.selectUserByUserId(note.getCreateUserId());
//							UserNote userNote = new UserNote(noteUser,note);
//							userNotes.add(userNote);
//						}
//						GroupNoteVo groupNote = new GroupNoteVo(user, group, userNotes);
//						groupNotes.add(groupNote);
//					}
//				}
//			}
//			return groupNotes;
//		} catch (Exception ex){
//			throw new ServiceException("获取待办事务信息失败",ex);
//		}
//	}

	/**
	 * 任务管理
	 */
	@Override
	public List<UserTaskVo> showNoFinishedTasks(User user) {
		try{
			List<UserTaskVo> userTaskVos = new ArrayList<UserTaskVo>();
			if(user != null){
				List<UserTask> userTasks = taskMapper.selectTaskIds(user);
				for(UserTask userTask : userTasks){
					if(userTask.getFinishTime() == null){
						Task task = taskMapper.selectTaskByTaskId(userTask.getTaskId());
						Group group = groupMapper.selectGroupByGroupId(task.getGroupId());
						User createUser = userMapper.selectUserByUserId(task.getCreateUserId());
						UserTaskVo userTaskVo = new UserTaskVo(createUser, group, task);
						userTaskVos.add(userTaskVo);
					}
				}
			}
			return userTaskVos;
		}catch(Exception ex){
			throw new ServiceException("查询失败",ex);
		}
	}
	
	@Override
	public List<UserTaskVo> showFinishedTasks(User user) {
		try{
			List<UserTaskVo> userTaskVos = new ArrayList<UserTaskVo>();
			if(user != null){
				List<UserTask> userTasks = taskMapper.selectTaskIds(user);
				for(UserTask userTask : userTasks){
					if(userTask.getFinishTime() != null){
						Task task = taskMapper.selectTaskByTaskId(userTask.getTaskId());
						Group group = groupMapper.selectGroupByGroupId(task.getGroupId());
						User createUser = userMapper.selectUserByUserId(task.getCreateUserId());
						UserTaskVo userTaskVo = new UserTaskVo(createUser, group, task);
						userTaskVos.add(userTaskVo);
					}
				}
			}
			return userTaskVos;
		}catch(Exception ex){
			throw new ServiceException("查询失败",ex);
		}
	}

	@Override
	public void finishTask(Integer taskId,User user) {
		try{
			if(user != null){
				UserTask userTask = taskMapper.selectUserTask(user.getId(), taskId);
				userTask.setFinishTime(new Date());
				taskMapper.updateUserTask(userTask);
			}
		}catch(Exception ex){
			throw new ServiceException("任务不存在",ex);
		}
	}

	@Override
	public List<UserInfromVo> showGroupInforms(Integer groupId) {
		try{
			List<UserInfromVo> userInforms = new ArrayList<UserInfromVo>();
			if(groupId != null){
				List<Inform> informs = informMapper.selectAllInforms(groupId);
				for(Inform inform : informs){
					User user = userMapper.selectUserByUserId(inform.getUserId());
					UserInfromVo userInform = new UserInfromVo(user, inform);
					userInforms.add(userInform);
				}
			}
			return userInforms;
		}catch(Exception ex){
			throw new ServiceException("查询失败",ex);
		}
	}

	@Override
	@Transactional
	public void saveTask(Integer groupId, String taskName, String taskContent, int[] userIds, String endTime, User createUser) {
		try{
			if(groupId != null && createUser != null){
				Task task = new Task();
				task.setGroupId(groupId);
				task.setCreateUserId(createUser.getId());
				task.setName(taskName);
				task.setContent(taskContent);
				task.setCreateTime(new Date());
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				if(endTime != null){
					Date endDate=sdf.parse(endTime);
					task.setEndTime(endDate);
				}
				taskMapper.addTask(task);
				
				int taskId = task.getId();
				for(int userId : userIds){
					UserTask userTask = new UserTask();
					userTask.setUserId(userId);
					userTask.setTaskId(taskId);
					taskMapper.insertUserTask(userTask);
				}
			}
		}catch(Exception ex){
			throw new ServiceException("任务添加失败",ex);
		}
	}
	
	@Override
	public List<TaskUsersVo> getTaskStatus(User user, Integer groupId) {
		try{
			List<TaskUsersVo> taskUsers = new ArrayList<TaskUsersVo>();
			if(user != null && groupId != null){
				List<Task> tasks = taskMapper.selectTaskByUserGroup(user.getId(), groupId);
				for(Task task : tasks){
					List<Integer> userIds = taskMapper.selectUserIds(task.getId());
					List<User> realUsers = new ArrayList<User>();
					for(int userId : userIds){
						User realUser = userMapper.selectUserByUserId(userId);
						realUsers.add(realUser);
					}
					TaskUsersVo taskUser = new TaskUsersVo(task, realUsers);
					taskUsers.add(taskUser);
				}
			}
			return taskUsers;
		}catch(Exception ex){
			throw new ServiceException("查询失败",ex);
		}
	}

	@Override
	public void addInform(Integer groupId,String informContent, User user) {
		try{
			Inform inform = new Inform();
			inform.setGroupId(groupId);
			inform.setUserId(user.getId());
			inform.setContent(informContent);
			inform.setCreateTime(new Date());
			
			informMapper.addInform(inform);
		}catch(Exception ex){
			throw new ServiceException("添加通知失败",ex);
		}
	}

	@Override
	public List<String> getGroupFiles(Integer groupId) {
		try{
			List<String> groupFiles = new ArrayList<String>();
			if(groupId != null){
				Group group  = groupMapper.selectGroupByGroupId(groupId);
				String groupName = group.getName();
				File groupDir = new File(rootDir,groupName.trim());
				File[] files = groupDir.listFiles();
				if(files != null){
					for(File file : files){
						groupFiles.add(file.getName());
					}
				}
			}
			return groupFiles;
		} catch (Exception ex){
			throw new ServiceException("查询失败",ex);
		}
	}

	@Override
	public File downloadGroupFile(Integer groupId, String fileName) {
		List<File> files = new ArrayList<>();
		FileUtils.searchFiles(fileName,new File(rootDir), files);
		if (files.size() > 1) {
			logger.error(String.format(" %s 文件出现多个，这可能是个系统错误！",fileName));
			return null;
		}
		if (files.size() > 0) {
			return files.get(0);
		}
		return null;
	}

	@Override
	public void uploadGroupFile(Integer groupId, MultipartFile[] groupFiles) {
		try{
			Group group  = groupMapper.selectGroupByGroupId(groupId);
			String groupName = group.getName();
			File groupDir = new File(rootDir,"/"+groupName.trim()+"/");
			for(int i=0;i<groupFiles.length;i++){
				if(groupFiles[i].isEmpty()){
					continue;
				}
				File uploadFile = new File(groupDir,groupFiles[i].getOriginalFilename());
				groupFiles[i].transferTo(uploadFile);
			}
		}catch(Exception ex){
			throw new ServiceException("上传失败",ex);
		}
	}

}
